﻿using AutoMapper;
using B.S.Sterilizationcenter.Domain.zmc;
using B.S.Sterilizationcenter.ErrorCode;
using B.S.Sterilizationcenter.Read.API.Appliaction.Commends.zmc;
using B.S.Sterilizationcenter.Read.API.Dto;
using MediatR;
using SqlSugar;

namespace B.S.Sterilizationcenter.Read.API.Appliaction.CommandHandlers.zmc
{
    public class QueryApparatusCommandHandlers : IRequestHandler<QueryApparatusCommand, ApiResult<List<ApparatusDto>>>
    {

        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public QueryApparatusCommandHandlers(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        /// <summary>
        /// 查询设备类型
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<ApparatusDto>>> Handle(QueryApparatusCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<List<ApparatusDto>> result = new ApiResult<List<ApparatusDto>>();

                result.Code = ApiEnums.查询成功;
                result.Msg = "查询成功";
                var list = db.Queryable<Apparatus>().LeftJoin<ApparatusType>((o, cus) => o.ApparatusTypeId == cus.ApparatusTypeId).Where(o => o.IsDeletes == false).Select((o, cus) => new ApparatusDto
                {
                    ApparatusId = o.ApparatusId,
                    ApparatusName = o.ApparatusName,
                    ApparatusNo = o.ApparatusNo,
                    ApparatusTypeId = o.ApparatusTypeId,
                    ApparatusNnit = o.ApparatusNnit,
                    Durableproperties = o.Durableproperties,
                   ApparatusPrice = o.ApparatusPrice,
                    ApparatusImg=cus.ApparatusImg,
                    ApparatusModel = o.ApparatusModel,
                    Productionindustry = o.Productionindustry,
                    ApparatusTypeName = cus.ApparatusTypeName

                }).ToList();
                if (!string.IsNullOrEmpty(request.ApparatusName))
                {
                    list = list.Where(it => it.ApparatusName.Contains(request.ApparatusName)).ToList();
                }
                if (!string.IsNullOrEmpty(request.ApparatusNo))
                {
                    list = list.Where(it => it.ApparatusNo.Contains(request.ApparatusNo)).ToList();
                }
                result.Data = mapper.Map<List<ApparatusDto>>(list.ToList());
                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
